package math;
import java.lang.Math;

import org.apache.commons.math3.distribution.TDistribution;

public class ConfidenceIntervall {
	public static double[] getIntervall(double[] items, double p) {
		double result[] = {0,0};
		double mean = getMean(items);
		double variance = getVariance(items, mean);
		
		
		double t_quantile = tVerteilung(p*100, items.length);//sd.cdf(p);
		result[0] = mean - t_quantile*Math.sqrt(variance)/Math.sqrt(items.length);
		result[1] = mean + t_quantile*Math.sqrt(variance)/Math.sqrt(items.length);
		return result;
	}
	private static double getMean(double[] items) {
		double result = 0;
		for(double item : items) {
			result += item;
		}
		result /= items.length;
		return result;
	}
	private static double getVariance(double[] items, double mean) {
		double result = 0;
		double temp;
		for(double item : items) {
			temp = (item - mean);
			result += (temp*temp);
		}
		result /= (items.length - 1);
		return result;
	}
	private static double tVerteilung(double vertrauensniveau, int anzahl) {
        int freiheitsgrad = anzahl - 1;
        double erwartungswahrscheinlichkeit = (100 - vertrauensniveau) / 100 / 2;
        TDistribution tDist = new TDistribution(freiheitsgrad);
        return -1 * tDist.inverseCumulativeProbability(erwartungswahrscheinlichkeit);
	}
}